//
//  RootViewController.m
//  06 美拍相机
//
//  Created by dllo on 16/3/17.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "RootViewController.h"
#import "PhotoMovieViewController.h"
#import "ImportVideoViewController.h"
#import "ImageFilterViewController.h"

#import <AVFoundation/AVFoundation.h>
#import <AssetsLibrary/AssetsLibrary.h>

typedef void(^PropertyChangeBlock)(AVCaptureDevice *captureDevice);
// 视频输出代理
@interface RootViewController ()<AVCaptureFileOutputRecordingDelegate>
// 负责输入和输出设置之间的数据传递
@property(nonatomic, strong)AVCaptureSession *captureSession;

// 负责从AVCaptureDevice获得输入数据
@property(nonatomic, strong)AVCaptureDeviceInput *captureDeviceInput;

// 照片输出流
@property(nonatomic, strong)AVCaptureStillImageOutput *captureStillImageOutput;

// 视频输出流
@property(nonatomic, strong)AVCaptureMovieFileOutput*captureMovieFileOutput;

// 后台任务标示
@property(nonatomic, assign)UIBackgroundTaskIdentifier backgroundTaskIdentifier;

// 相机拍摄预览图层
@property(nonatomic, strong)AVCaptureVideoPreviewLayer *captureVideoPreviewLayer;

// 显示摄像头内容
@property (strong, nonatomic) IBOutlet UIView *viewContainer;

// 聚焦的图标
@property (strong, nonatomic) IBOutlet UIImageView *FocusCursor;

// 照片电影的图标
@property (strong, nonatomic) IBOutlet UIImageView *photoMovieImageView;
// 照片电影的Label
@property (strong, nonatomic) IBOutlet UILabel *photoMovieLabel;

// 导入视频的图标
@property (strong, nonatomic) IBOutlet UIImageView *importMovieImageView;

// 导入视频的Label
@property (strong, nonatomic) IBOutlet UILabel *importMovieLabel;

// 显示进度条的背景视图
@property (strong, nonatomic) IBOutlet UIView *progressBackView;

// 显示进度的Label
@property (strong, nonatomic) IBOutlet UILabel *progressLabel;

// 显示进度的视图
@property(nonatomic, strong)UIView *progressView;

// 计时器
@property(nonatomic, strong)NSTimer *progressTimer;

// 记录时间
@property(nonatomic, assign)NSInteger duration;

// 开启闪光灯的方法
- (IBAction)tabkeFlashButton:(id)sender;
// 切换摄像头
- (IBAction)toggleButton:(id)sender;

// 记录当前是拍照还是摄像
@property(nonatomic, assign)BOOL isTakePhoto;

// 拍照按钮
@property (strong, nonatomic) IBOutlet UIButton *takePhotoButton;

// 录制视频按钮
@property (strong, nonatomic) IBOutlet UIButton *takeVideoButton;


@end

@implementation RootViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    // 初始化选择类型
    self.isTakePhoto = YES;
    [self.takePhotoButton setTitleColor:[UIColor colorWithRed:224 / 255.0 green:32 / 255.0 blue:76 / 255.0 alpha:1] forState:UIControlStateNormal];
    [self.takeVideoButton setTitleColor:[UIColor colorWithRed:231 / 255.0 green:231 / 255.0 blue:231 / 255.0 alpha:1] forState:UIControlStateNormal];
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    // 初始化视图
    [self.photoMovieImageView setImage:[UIImage imageNamed:@"icon_choose_photo_a@3x"]];
    self.photoMovieLabel.textColor = [UIColor lightGrayColor];
    
    [self.importMovieImageView setImage:[UIImage imageNamed:@"icon_photo_library_a@3x"]];
    self.importMovieLabel.textColor = [UIColor lightGrayColor];
    
    // 初始化回话
    _captureSession = [[AVCaptureSession alloc] init];
    if([_captureSession canSetSessionPreset:AVCaptureSessionPreset1280x720]){
        // 设置分辨率
        _captureSession.sessionPreset = AVCaptureSessionPreset1280x720;
    }
    // 获得输入设备
    AVCaptureDevice *captureDevice = [self getCameraDeviceWithPosition:AVCaptureDevicePositionBack]; // 获取后置摄像头
    
    if(!captureDevice){
        NSLog(@"取得后置摄像头的时候出现问题");
        return;
    }
    NSError *error = nil;
    // 添加一个音频输入设备
    AVCaptureDevice *audioCaptureDevice = [[AVCaptureDevice devicesWithMediaType:AVMediaTypeAudio] firstObject];
    
    // 根据输入设备初始化设置输入对象,用于获取输入数据
    _captureDeviceInput = [[AVCaptureDeviceInput alloc] initWithDevice:captureDevice error:&error];
    if(error){
        NSLog(@"获取设备输入对象时出错,错误原因: %@",error.localizedDescription);
        return;
    }
    
    AVCaptureDeviceInput *audioCaptureDeviceInput = [[AVCaptureDeviceInput alloc] initWithDevice:audioCaptureDevice error:&error];
    if(error){
        NSLog(@"获取音频输入设备对象时出错,错误信息: %@",error.localizedDescription);
    }
    
    // 初始化设备输出对象,用于获得 拍照 输出数据
    _captureStillImageOutput = [[AVCaptureStillImageOutput alloc] init];
    NSDictionary *outputSettings = @{AVVideoCodecKey:AVVideoCodecJPEG};
    // 输出设置
    [self.captureStillImageOutput setOutputSettings:outputSettings];
    
    // 初始化设备输出对象,用于获得 录像 输出设备
    _captureMovieFileOutput = [[AVCaptureMovieFileOutput alloc] init];
    
    // 将设备输入添加到会话中
    if([self.captureSession canAddInput:self.captureDeviceInput]){
        [self.captureSession addInput:self.captureDeviceInput];
        [self.captureSession addInput:audioCaptureDeviceInput];;
        AVCaptureConnection *captureConnection = [_captureMovieFileOutput connectionWithMediaType:AVMediaTypeVideo];
        if([captureConnection isVideoStabilizationSupported]){
            captureConnection.preferredVideoStabilizationMode = AVCaptureVideoStabilizationModeAuto;
        }
    }
    
    // 将设备输出添加到会话中
    if([self.captureSession canAddOutput:self.captureStillImageOutput]){
        [self.captureSession addOutput:self.captureStillImageOutput];
    }
    if([_captureSession canAddOutput:_captureMovieFileOutput]){
        [_captureSession addOutput:_captureMovieFileOutput];
    }
    
    
    // 创建视频预览层,用于实时展示摄像头状态
    self.captureVideoPreviewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:self.captureSession];
    
    CALayer *layer =  self.viewContainer.layer;
    layer.masksToBounds = YES;
    
//    _captureVideoPreviewLayer.frame = layer.bounds;
    _captureVideoPreviewLayer.frame = CGRectMake(0, 0, 400, 450);
    // 填充模式
    _captureVideoPreviewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
    
    // 将视频预览层添加到界面中
    [layer insertSublayer:self.captureVideoPreviewLayer below:self.FocusCursor.layer];
    
    [self addNotificationToCaptureDevice:captureDevice];
    [self addGenstureRecognizer];
    
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [self.captureSession startRunning];
}

- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    [self.captureSession stopRunning];
}
- (void)dealloc{
    [self removeNotification];
}



// 照片电影的轻点方法
- (IBAction)clickPhotoMovieView:(id)sender {
    
    [self.photoMovieImageView setImage:[UIImage imageNamed:@"icon_choose_photo_b@3x"]];
    self.photoMovieLabel.textColor = [UIColor colorWithRed:224 / 255.0 green:32 / 255.0 blue:76 / 255.0 alpha:1];
    
    PhotoMovieViewController *photoVC = [[PhotoMovieViewController alloc] initWithNibName:NSStringFromClass([PhotoMovieViewController class]) bundle:nil];
    
    [self presentViewController:photoVC animated:NO completion:^{
    }];
}
// 点击导入视频视图的触发2方法
- (IBAction)clickImportMovieView:(id)sender {
    
    [self.importMovieImageView setImage:[UIImage imageNamed:@"icon_photo_library_b@3x"]];
    self.importMovieLabel.textColor = [UIColor colorWithRed:224 / 255.0 green:32 / 255.0 blue:76 / 255.0 alpha:1];
    
    ImportVideoViewController *importVideoVC = [[ImportVideoViewController alloc] initWithNibName:NSStringFromClass([ImportVideoViewController class]) bundle:nil];
    
    [self presentViewController:importVideoVC animated:YES completion:^{
        
        
    }];
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

#pragma mark 通知
/**
 *  给设备添加通知
 */
- (void)addNotificationToCaptureDevice:(AVCaptureDevice *)captureDevice{
    
    // 注意添加区域改变捕获通知必须首先设置设备允许捕获
    [self changeDeviceProperty:^(AVCaptureDevice *captureDevice) {
        captureDevice.subjectAreaChangeMonitoringEnabled = YES;
    }];
    
    NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
    // 捕获区域发生改变
    [notificationCenter addObserver:self selector:@selector(areaChange:) name:AVCaptureDeviceSubjectAreaDidChangeNotification object:captureDevice];
}
/**
 *  移除通知
 */
- (void)removeNotificationFromCaptureDevice:(AVCaptureDevice *)captureDevice{
    NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
    [notificationCenter removeObserver:self name:AVCaptureDeviceSubjectAreaDidChangeNotification object:captureDevice];
}

/**
 *  移除所有通知
 */
- (void)removeNotification{
    NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
    [notificationCenter removeObserver:self];
}
- (void)addNotificationToCaptureSession:(AVCaptureSession *)captureSession{
    NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
    // 会话出错
    [notificationCenter addObserver:self selector:@selector(sessionRuntimeError:) name:AVCaptureSessionRuntimeErrorNotification object:captureSession];
}
/**
 *  设备链接成功
 *
 *  @param notification 通知对象
 */
- (void)deviceConnected:(NSNotification *)notification{
    NSLog(@"设备已链接...");
}
/**
 *  设备链接断开
 *
 *  @param notification 通知对象
 */
- (void)deviceDisconnected:(NSNotification *)notification{
    NSLog(@"设备已断开...");
}

/**
 *  捕获区域改变
 *
 *  @param notification 通知对象
 */

- (void)areaChange:(NSNotification *)notification{
//    NSLog(@"捕获区域改变...");
}

/**
 *  会话出错
 *
 *  @param notification 通知对象
 */
- (void)sessionRuntimeError:(NSNotification *)notification{
    NSLog(@"会话发生错误..");
}



#pragma mark 自定义方法

/**
 *  获取指定位置的摄像头
 *
 *  @param position 摄像头的位置 前还是后
 *
 *  @return 摄像头设置
 */

- (AVCaptureDevice *)getCameraDeviceWithPosition:(AVCaptureDevicePosition )position{
    NSArray *cameras = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
    for(AVCaptureDevice *camera in cameras){
        if([camera position] == position){
            return camera;
        }
    }
    return nil;
}

/**
 *  改变设置属性的同意操作方法
 *
 *  @param propertyChange 属性改变操作
 */

- (void)changeDeviceProperty:(PropertyChangeBlock)propertyChange{
    AVCaptureDevice *captureDevice = [self.captureDeviceInput device];
    NSError *error;
    // 注意改变设备属性前一定要首先调用lockForConfiguration:锁上,调用完后使用unlockForConfiguration方法解锁
    if([captureDevice lockForConfiguration:&error]){
        propertyChange(captureDevice);
        [captureDevice unlockForConfiguration];
    }
    else{
        NSLog(@"设置设备属性过程发生错误, 错误信息:%@",error.localizedDescription);
    }
}

/**
 *  添加点击方法
 */

- (void)addGenstureRecognizer{
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapScreen:)];
    [self.viewContainer addGestureRecognizer:tapGesture];
}

- (void)tapScreen:(UITapGestureRecognizer *)tapGesture{
    
    NSLog(@"点击");
    
    // 获得点击的位置
    CGPoint point = [tapGesture locationInView:self.viewContainer];
    // 将点击的坐标转化为摄像头的坐标
    CGPoint cameraPoint = [self.captureVideoPreviewLayer captureDevicePointOfInterestForPoint:point];
    [self setFocusCursorWithPoint:point];
    [self focusWithMode:AVCaptureFocusModeContinuousAutoFocus exposureMode:AVCaptureExposureModeAutoExpose atPoint:cameraPoint];
}

/**
 *  设置聚焦点
 *
 *  @param point  聚焦点
 */
- (void)focusWithMode:(AVCaptureFocusMode)focusMode exposureMode:(AVCaptureExposureMode)exposureMode atPoint:(CGPoint)point{
   [self changeDeviceProperty:^(AVCaptureDevice *captureDevice) {
       
       if([captureDevice isFocusModeSupported:focusMode]){
           [captureDevice setFocusMode:AVCaptureFocusModeAutoFocus];
       }
       if([captureDevice isFocusPointOfInterestSupported]){
           [captureDevice setFocusPointOfInterest:point];
       }
       if([captureDevice isExposureModeSupported:exposureMode]){
           [captureDevice setExposureMode:AVCaptureExposureModeAutoExpose];
       }
       if([captureDevice isExposurePointOfInterestSupported]){
           [captureDevice setExposurePointOfInterest:point];
       }
       
   }];
}

/**
 *  设置聚焦光标的位置
 *
 *  @param point 光标的位置
 */
-  (void)setFocusCursorWithPoint:(CGPoint)point{
    self.FocusCursor.center = point;
    self.FocusCursor.transform = CGAffineTransformMakeScale(1.5, 1.5);
    self.FocusCursor.alpha = 1.0;
    [UIView animateWithDuration:1.0 animations:^{
        
        self.FocusCursor.transform = CGAffineTransformIdentity;
        
    } completion:^(BOOL finished) {
        
        self.FocusCursor.alpha = 0;
    }];
}
/**
 *  设置闪光灯模式
 *
 *  @param flashMode 闪光灯模式
 */
- (void)setFlashMode:(AVCaptureFlashMode)flashMode{
    [self changeDeviceProperty:^(AVCaptureDevice *captureDevice) {
        if([captureDevice isFlashModeSupported:flashMode]){
            [captureDevice setFlashMode:flashMode];
        }
    }];
}
/**
 *  录像开始的时候启动计时器
 */
- (void)startTimer{
    
    if(self.progressTimer == nil){
        self.progressTimer = [NSTimer timerWithTimeInterval:0.1 target:self selector:@selector(updateProgress) userInfo:nil repeats:YES];
        [[NSRunLoop mainRunLoop] addTimer:self.progressTimer forMode:NSDefaultRunLoopMode];
        
        self.duration = 0;
        self.progressLabel.alpha = 1.0;
        self.progressView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 10)];
        [self.progressBackView addSubview:self.progressView];
        self.progressView.backgroundColor = [UIColor redColor];
        self.progressLabel.text = @"0.0秒";
        [self.progressTimer fire];
    }
    self.progressTimer.fireDate = [NSDate distantPast];
}
/**
 *  更新进度
 */
- (void)updateProgress{
    self.duration ++;
    if(self.duration / 10 == 60){
        [self.captureMovieFileOutput stopRecording];
        [self pauseTimer];
    }
    else{
        self.progressLabel.text = [NSString stringWithFormat:@"%ld.%ld秒",(self.duration / 10), (self.duration % 10)];
        self.progressView.frame = CGRectMake(0, 0, self.progressBackView.frame.size.width / 60.0 * self.duration / 10, 10);
    }
}
/**
 *  暂停计时器
 */
- (void)pauseTimer{
    self.progressTimer.fireDate = [NSDate distantFuture];
}
/**
 *  撤销计时器
 */
- (void)cancelTimer{
    [self.progressTimer invalidate];
    self.progressTimer = nil;
    self.progressLabel.alpha = 0;
    self.progressView.frame = CGRectMake(0, 0, 0, 0);
}
/**
 *  将视频保存到相簿中
 *
 *  @param outputFileURL 视频的地址
 */
- (void)saveVideoToAlbumOutputFileURL:(NSURL *)outputFileURL{
    // 视频录入完成后在后台将视频存储到相簿
    UIBackgroundTaskIdentifier lastBackgroundTaskidentifier = self.backgroundTaskIdentifier;
    self.backgroundTaskIdentifier = UIBackgroundTaskInvalid;
    ALAssetsLibrary *assetsLibrary = [[ALAssetsLibrary alloc] init];
    [assetsLibrary writeVideoAtPathToSavedPhotosAlbum:outputFileURL completionBlock:^(NSURL *assetURL, NSError *error) {
        if(error){
            NSLog(@"保存视频到相簿过程中发生错误,错误信息%@",error.localizedDescription);
        }
        [[NSFileManager defaultManager] removeItemAtURL:outputFileURL error:nil];
        if(lastBackgroundTaskidentifier != UIBackgroundTaskInvalid){
            [[UIApplication sharedApplication] endBackgroundTask:lastBackgroundTaskidentifier];
        }
        NSLog(@"成功保存视频到相簿.");
    }];
}

#pragma mark UI方法
#pragma mark 点击中心按钮,拍照或录像
- (IBAction)clickCenterButton:(id)sender {
    if(self.isTakePhoto){
        [self takePhoto];
    }
    else{
        [self takeVideo];
    }
}
// 点击选择拍照
- (IBAction)selecteTakePhoto:(UIButton *)sender {
    // 设置类型
    self.isTakePhoto = YES;
    [self.takePhotoButton setTitleColor:[UIColor colorWithRed:224 / 255.0 green:32 / 255.0 blue:76 / 255.0 alpha:1] forState:UIControlStateNormal];
    [self.takeVideoButton setTitleColor:[UIColor colorWithRed:231 / 255.0 green:231 / 255.0 blue:231 / 255.0 alpha:1] forState:UIControlStateNormal];
}

// 点击选择录制视频
- (IBAction)selecteTakeVideo:(id)sender {
    // 设置类型
    self.isTakePhoto = NO;
    [self.takePhotoButton setTitleColor:[UIColor colorWithRed:231 / 255.0 green:231 / 255.0 blue:231 / 255.0 alpha:1] forState:UIControlStateNormal];
    [self.takeVideoButton setTitleColor:[UIColor colorWithRed:224 / 255.0 green:32 / 255.0 blue:76 / 255.0 alpha:1] forState:UIControlStateNormal];
}
#pragma mark 退出拍照录像界面
- (IBAction)clickQuit:(id)sender {
    [self dismissViewControllerAnimated:YES completion:^{
        
        
    }];
}

// 拍照的方法
#pragma mark 拍摄照片
/**
 *  拍摄照片
 */
- (void)takePhoto{
    NSLog(@"拍照");
    
    // 根据设备输出获取的数据
    AVCaptureConnection *captureConnection = [self.captureStillImageOutput connectionWithMediaType:AVMediaTypeVideo];
    // 根据连接取得设备输出的数据
    [self.captureStillImageOutput captureStillImageAsynchronouslyFromConnection:captureConnection completionHandler:^(CMSampleBufferRef imageDataSampleBuffer, NSError *error) {
        
        if(imageDataSampleBuffer){
            NSData *imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer];
            UIImage *image = [UIImage imageWithData:imageData];
            ImageFilterViewController *imageFilterVC = [[ImageFilterViewController alloc] initWithNibName:NSStringFromClass([ImageFilterViewController class]) bundle:nil];
            imageFilterVC.image = image;
            [self presentViewController:imageFilterVC animated:NO completion:^{
                
            }];
        }
    }];
    
//    ImageFilterViewController *imageFilterVC = [[ImageFilterViewController alloc] initWithNibName:NSStringFromClass([ImageFilterViewController class]) bundle:nil];
//    imageFilterVC.image = [UIImage imageNamed:@"1"];
//    [self presentViewController:imageFilterVC animated:NO completion:^{
//        
//    }];
    
}

#pragma mark 录制视频
/**
 *  录制视频
 */
- (void)takeVideo{
    NSLog(@"录制视频");
    
    // 根据设备输出获得的连接
    AVCaptureConnection *captureConnection = [self.captureMovieFileOutput connectionWithMediaType:AVMediaTypeVideo];
    // 根据连接获取设备输出的数据
    if(![self.captureMovieFileOutput isRecording]){
        // 如果支持多任务则开始多任务
        if([[UIDevice currentDevice] isMultitaskingSupported]){
            self.backgroundTaskIdentifier = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:nil];
        }
        // 预览突出和视频的方向保持一致
        captureConnection.videoOrientation = [self.captureVideoPreviewLayer connection].videoOrientation;
        NSString *outputFilePath = [NSTemporaryDirectory() stringByAppendingString:@"myMovie.mov"];
        NSLog(@"视频保持的路径 :%@",outputFilePath);
        NSURL *fileUrl = [NSURL fileURLWithPath:outputFilePath];
        [self.captureMovieFileOutput startRecordingToOutputFileURL:fileUrl recordingDelegate:self];
        
    }
    else{
        // 停止录制
        [self.captureMovieFileOutput stopRecording];
    }
}
#pragma mark 开启闪光灯
- (IBAction)tabkeFlashButton:(id)sender {
    NSLog(@"开启闪光灯");
    [self setFlashMode:AVCaptureFlashModeOn];
}

#pragma mark 切换摄像头
- (IBAction)toggleButton:(id)sender {
    NSLog(@"切换摄像头");
    
    AVCaptureDevice *currentDevice = [self.captureDeviceInput device];
    AVCaptureDevicePosition currentPosition = [currentDevice position];
    [self removeNotificationFromCaptureDevice:currentDevice];
    AVCaptureDevice *toChangeDevice;
    AVCaptureDevicePosition toChangePosition = AVCaptureDevicePositionFront;
    if(currentPosition == AVCaptureDevicePositionUnspecified ||
       currentPosition == AVCaptureDevicePositionFront){
        toChangePosition = AVCaptureDevicePositionBack;
    }
    toChangeDevice = [self getCameraDeviceWithPosition:toChangePosition];
    [self addNotificationToCaptureDevice:toChangeDevice];
    // 获得需要调整的设备输入对象
    AVCaptureDeviceInput *toChangeDeviceInput = [[AVCaptureDeviceInput alloc] initWithDevice:toChangeDevice error:nil];
    
    // 改变会话的设置前一定要先开启配制,配制完成后提交配制改变
    [self.captureSession beginConfiguration];
    // 移除原有输入对象
    [self.captureSession removeInput:self.captureDeviceInput];
    // 添加新的输入对象
    if([self.captureSession canAddInput:toChangeDeviceInput]){
        [self.captureSession addInput:toChangeDeviceInput];
        self.captureDeviceInput = toChangeDeviceInput;
    }
    // 提交会话配制
    [self.captureSession commitConfiguration];
}
#pragma mark 视频输出协议方法
- (void)captureOutput:(AVCaptureFileOutput *)captureOutput didStartRecordingToOutputFileAtURL:(NSURL *)fileURL fromConnections:(NSArray *)connections{
    NSLog(@"开始录制视频...");
    
    // 开始计时
    [self startTimer];
}
- (void)captureOutput:(AVCaptureFileOutput *)captureOutput didFinishRecordingToOutputFileAtURL:(NSURL *)outputFileURL fromConnections:(NSArray *)connections error:(NSError *)error{
    NSLog(@"视频录制完成...");

    // 停止计时
    [self pauseTimer];
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"确定保存这个视频吗?" message:@"" preferredStyle:UIAlertControllerStyleAlert];
    // Action
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        // 保存视频到相簿
        [self saveVideoToAlbumOutputFileURL:outputFileURL];
    }];
    
    // CancelAction
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        // 清空计时
        [self cancelTimer];
        
    }];
    
    // 添加
    [alert addAction:action];
    [alert addAction:cancelAction];
    // 显示
    [self presentViewController:alert animated:YES completion:^{
    }];
}

@end
